package com.cos.shop.web.controller;

import com.alibaba.fastjson.JSON;
import com.cos.shop.common.Const;
import com.cos.shop.common.ResponseCode;
import com.cos.shop.common.ResponseResult;
import com.cos.shop.services.UserServices;
import com.cos.shop.services.impl.UserServicesImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author: COS
 * @time: 2023/5/9 11:29
 * @description:
 */
@WebServlet("/sys")
public class SystemController extends BaseServlet {
    private UserServices us = new UserServicesImpl();

    /**
     * @author: COS
     * @time: 2023/5/10 11:14
     * @description: 处理用户账户激活
     */
    public String activate(HttpServletRequest request, HttpServletResponse response) {
        String e = request.getParameter("e");
        String c = request.getParameter("c");
        // 访问业务处理激活业务
        ResponseResult rr = us.activate(e, c);
        // 存放request作用域
        request.setAttribute("msg", rr);
        return Const.MESSAGE;
    }
    /**
     * @author: COS
     * @time: 2023/5/10 15:51
     * @description: 发送手机短信
     */
    public String sendMessage(HttpServletRequest request, HttpServletResponse response) {
        String phone = request.getParameter("phone");
        // 调用业务层 发送手机短信
        ResponseResult rr = us.sendMessage(phone);
        if (rr.getCode()== ResponseCode.SUCCESS.getCode()) {
            // 已经发送短信
            // 保存验证码到session中, 让前端去验证
            request.getSession().setAttribute(Const.MESSAGE_CODE,rr.getMsg());
        }
        String s = JSON.toJSONString(rr);
        return s;
    }

    public String checkCode(HttpServletRequest request, HttpServletResponse response) {
        //1 接受数据
        String code = request.getParameter("code");
        String messageCode = (String) request.getSession().getAttribute(Const.MESSAGE_CODE);
        if (messageCode.equals(code)) {
            return JSON.toJSONString(ResponseResult.createSuccess("验证码正确"));
        }
        return  JSON.toJSONString(ResponseResult.createFail("验证码错误"));
    }
}